// miniprogram/pages/appointment/appointment.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    min: 1, //最少字数
    max: 520,
    files: [],
    images_fileID: [],
    last: 0,
    reservation_number:[1,2,0,3,4],
    items: [
      {value: 'MON', name: '星期一',cs:3,disable:false, checked:false},
      {value: 'FUE', name: '星期二',cs:0,disable:false, checked:false},
      {value: 'WED', name: '星期三',cs:2,disable:false, checked:false},
      {value: 'THU', name: '星期四',cs:0,disable:false, checked:false},
      {value: 'FRI', name: '星期五',cs:4,disable:false, checked:false},
    ]
  },
  onLoad: function(e) {
    var that = this
    const db = wx.cloud.database()
    db.collection('admin').where({
      _id: ' oMr_G5PFfqcEsZPWQhX5qxQ-AjH8'

    }).get({
      success: res => {
        that.setData({
          title1: res.data[0].title_app
        })
      },
      fail: err => {
        wx.showToast({
          icon: "none",
          title: '查询记录失败',
        })
      }
    })
    for(let i=0;i<5;i++){
   
    if(this.data.items[i].cs==0){
       this.data.items[i].disable=true;
     } 
     // console.log(this.data.items[i].disable)
   }
   var disable=this.data.items
   this.setData({
     items:disable
   })
 },
 radioChange(e) {
   //console.log('radio发生change事件，携带value值为：', e.detail.value)
   const items = this.data.items
   for (let i = 0, len = items.length; i < len; ++i) {
     items[i].checked = items[i].value === e.detail.value
   }
   this.setData({
     items
   })
  },

  inputs: function(e) { // 这个用来记录问题框的字数，虽然没什么用就，就是搞得好看的。
    // 获取输入框的内容
    var value = e.detail.value;
    // 获取输入框内容的长度
    var len = parseInt(value.length);

    this.setData({
      currentWordNumber: len //当前字数  
    });

  },

  chooseImage: function(e) { // 选择图片
    var that = this;
    let len = 0;
    if (that.data.files != null) {
      len = that.data.files.length; // 确定图片的数量，目的是限制图片只能上传三张
    } //获取当前已有的图片
    wx.chooseImage({
      count: 3 - len, //  图片的数量
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        that.data.photo = that.data.files.concat(res.tempFilePaths)
        that.setData({
          files: that.data.files.concat(res.tempFilePaths),
        });
        console.log(that.data.photo)
      }
    })
  },
  deleteImage: function(e) { // 很明显这个函数是用来删除已选择的图片
    var that = this;
    var files = that.data.files;
    var index = e.currentTarget.dataset.index; //获取当前长按图片下标

    wx.showModal({
      title: '提示',
      content: '确定要删除此图片吗？',
      success: function(res) {
        if (res.confirm) {
          console.log('点击确定了');
          files.splice(index, 1);
        } else if (res.cancel) {
          console.log('点击取消了');
          return false;
        }
        that.setData({
          files
        });
      }
    })
  },

  previewImage: function(e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    })
  },

  shangchuan: function(e) {
   
    var that = this;
    var time1 = Date.parse(new Date());
    var time = time1 - that.data.last;
    if (time > 5000) {
      var imageFiles = that.data.files;
      var date = new Date();
      var now = date.getFullYear() + "/" + ((date.getMonth() + 1) < "10" ? ("0" + (date.getMonth() + 1)) : (date.getMonth() + 1)) + "/" + (date.getDate() < "10" ? ("0" + date.getDate()) : date.getDate()) + " " + (date.getHours() < "10" ? ("0" + date.getHours()) : date.getHours()) + ":" + (date.getMinutes() < "10" ? ("0" + date.getMinutes()) : date.getMinutes()) + ":" + (date.getSeconds() < "10" ? ("0" + date.getSeconds()) : date.getSeconds()); // 记录一下上传的时间
      wx.cloud.init();
      const db = wx.cloud.database(); //初始化数据库
      const items = this.data.items
      var appointment_time1=''
      var cs=''
      for (let i = 0, len = items.length; i < len; ++i) {
        if(items[i].checked==true){
          appointment_time1=items[i].name
          cs=items[i].cs
        }
      }
     
      if (imageFiles.length) {
        //for循环进行图片上传
        for (var i = 0; i < imageFiles.length; i++) {
          var imageUrl = imageFiles[i].split("/");
          var name = imageUrl[imageUrl.length - 1]; //得到图片的名称
          var images_fileID = that.data.images_fileID; //得到data中的fileID
          wx.cloud.uploadFile({
            cloudPath: "question/" + name, //云存储路径
            filePath: imageFiles[i], //文件临时路径
            success: res => {
              images_fileID.push(res.fileID);
              that.setData({
                images_fileID: images_fileID //更新data中的 fileID
              })
              if (images_fileID.length === imageFiles.length) {
                //对数据库进行操作
                if (e.detail.value.name.length == 0) {
                  wx.showModal({
                    title: '姓名为空',
                    content: '请输入您的名字！',
                    showCancel: false,
                    confirmColor: '#f00'
                  })
                } else if (e.detail.value.address.length == 0) {
                  wx.showModal({
                    title: '地址为空',
                    content: '请填写您的地址！',
                    showCancel: false,
                    confirmColor: '#f00'
                  })
                } else if (e.detail.value.contact_way.length == 0) {
                  wx.showModal({
                    title: '联系方式为空',
                    content: '请填写您的联系方式！',
                    showCancel: false,
                    confirmColor: '#f00'
                  })
                } else if (e.detail.value.question.length == 0) {
                  wx.showModal({
                    title: '问题描述为空',
                    content: '请填写您的问题！',
                    showCancel: false,
                    confirmColor: '#f00'
                  })
                } else if (appointment_time1.length == 0) {
                  wx.showModal({
                    title: '预约时间为空',
                    content: '请选择您的预约时间！',
                    showCancel: false,
                    confirmColor: '#f00'
                  })
                } else {
                  // console.log(this.data)
                  for (let i = 0, len = items.length; i < len; ++i) {
                    if(items[i].checked==true){
                      items[i].cs=items[i].cs-1
                      cs=items[i].cs
                    }
                    // console.log(items[i].cs)
                  }
                  this.setData({
                    items
                  })
                  const db = wx.cloud.database()
                  db.collection('appointment').add({
                    data: {
                      name: e.detail.value.name,
                      address: e.detail.value.address,
                      contact_way: e.detail.value.contact_way,
                      question: e.detail.value.question,
                      appointment_time: appointment_time1,
                      reservation_number: cs,
                      status: '等待中',
                      serviceman: '暂未分配',
                      serviceContact_way: '暂未分配',
                      time: now,
                      // images: imageFiles,
                      images_fileID: that.data.images_fileID,
                      send:'0',
                      yuyueshijian:'today'
                    },
                    success: res => {
                      // utils.hideLoading()
                      // 在返回结果中会包含新创建的记录的 _id
                      this.setData({
                        name: e.detail.value.name,
                        address: e.detail.value.address,
                        contact_way: e.detail.value.contact_way,
                        question: e.detail.value.question,
                        appointment_time: appointment_time1,
                        reservation_number: cs,
                        time: now,
                        //这里需要回显预约时间
                      })
                      wx.showToast({
                        title: '预约提交成功',
                        duration: 2000,
                        mask: true,
                        success: function() {
                          setTimeout(function() {
                            wx.redirectTo({
                              url: '../status/status',
                            })
                          }, 2000)
                          // wx.redirectTo({
                          //   url: '../status/status',
                          // })
                        }
                      })
                      
                      // console.log('[数据库] [新增记录] 成功，记录 _id: ', res._id),
                      // console.log(e)
                    },
                    fail: err => {
                      // utils.hideLoading()
                      wx.showToast({
                        icon: 'none',
                        title: '预约提交失败'
                      })
                      console.error('[数据库] [新增记录] 失败：', err)
                    }
                  })
                  
                }

              }
            }
          })
        }
      } else {
        //对数据库进行操作
        if (e.detail.value.name.length == 0) {
          wx.showModal({
            title: '姓名为空',
            content: '请输入您的名字！',
            showCancel: false,
            confirmColor: '#f00'
          })
        } else if (e.detail.value.address.length == 0) {
          wx.showModal({
            title: '地址为空',
            content: '请填写您的地址！',
            showCancel: false,
            confirmColor: '#f00'
          })
        } else if (e.detail.value.contact_way.length == 0) {
          wx.showModal({
            title: '联系方式为空',
            content: '请填写您的联系方式！',
            showCancel: false,
            confirmColor: '#f00'
          })
        } else if (e.detail.value.question.length == 0) {
          wx.showModal({
            title: '问题描述为空',
            content: '请填写您的问题！',
            showCancel: false,
            confirmColor: '#f00'
          })
        } else if (appointment_time1.length == 0) {
          wx.showModal({
            title: '预约时间为空',
            content: '请选择您的预约时间！',
            showCancel: false,
            confirmColor: '#f00'
          })
        } else {
          for (let i = 0, len = items.length; i < len; ++i) {
            if(items[i].checked==true){
              items[i].cs=items[i].cs-1
              cs=items[i].cs
              console.log(items[i].cs)
            }  
          }
          this.setData({
            items
          })
          console.log(this.data)
          const db = wx.cloud.database()
          db.collection('appointment').add({
            data: {
              name: e.detail.value.name,
              address: e.detail.value.address,
              contact_way: e.detail.value.contact_way,
              question: e.detail.value.question,
              appointment_time: appointment_time1,
              reservation_number: cs,
              status: '等待中',
              serviceman: '暂未分配',
              serviceContact_way: '暂未分配',
              time: now,
              images_fileID: that.data.images_fileID,
              send:'0'
            },
            
            success: res => {
              // 在返回结果中会包含新创建的记录的 _id
              // util.hideLoading()
              this.setData({
                name: e.detail.value.name,
                address: e.detail.value.address,
                contact_way: e.detail.value.contact_way,
                question: e.detail.value.question,
                appointment_time:appointment_time1,
                reservation_number: cs,
                time: now,
              })

              // wx.showToast({
              //   title: '预约提交成功',
              // })
              // wx.redirectTo({
              //   url: '../status/status',
              // })
              wx.showToast({
                title: '预约提交成功',
                duration: 2000,
                mask: true,
                success: function() {
                  setTimeout(function() {
                    wx.redirectTo({
                      url: '../status/status',
                    })
                  }, 2000)
                  // setTimeout(function() {
                  //   wx.redirectTo({
                  //     url: '../status/status',
                  //   })
                  // }, 2000)
                  // wx.redirectTo({
                  //   url: '../status/status',
                  // })
                }
              })      
           
            },
            fail: err => {
              wx.showToast({
                icon: 'none',
                title: '预约提交失败'
              })
              console.error('[数据库] [新增记录] 失败：', err)
            }
          })
          
        
        }
      }
      that.data.last = time1;
    }
  },
  onShareAppMessage: function() {

  },
})